package spring.cloud.tasks.client;

import lombok.extern.slf4j.Slf4j;
import spring.cloud.tasks.common.zookeeper.ZooKeeperBatchTaskDataManager;
import spring.cloud.tasks.common.zookeeper.ZooKeeperItemTaskDataManager;

import java.util.Properties;


@Slf4j
public class Client {
    private static volatile boolean inited = false;
    private static ItemTaskWorker itemTaskWorker;
    private static BatchTaskWorker batchTaskWorker;


    public synchronized static boolean init() throws Exception {
        if (inited) {
            return true;
        }
        if (itemTaskWorker == null) {
            itemTaskWorker = new ItemTaskWorker();
            itemTaskWorker.executeTasks = false;
            Properties properties = new Properties();
            itemTaskWorker.init(properties);
            itemTaskWorker.executeTasks = true;
        }
        if (batchTaskWorker == null) {
            batchTaskWorker = new BatchTaskWorker();
            batchTaskWorker.executeTasks = false;
            Properties properties = new Properties();
            batchTaskWorker.init(properties);
            batchTaskWorker.executeTasks = true;
        }
        inited = true;
        return true;
    }


    public static void setWorker(Worker worker) {
        if (worker == null) {
            return;
        }
        if (worker instanceof ItemTaskWorker) {
            setItemTaskWorker((ItemTaskWorker) worker);
        } else if (worker instanceof BatchTaskWorker) {
            setBatchTaskWorker((BatchTaskWorker) worker);
        } else {
            throw new IllegalStateException();
        }
    }

    public static void setItemTaskWorker(ItemTaskWorker itemTaskWorker) {
        Client.itemTaskWorker = itemTaskWorker;
    }

    public static void setBatchTaskWorker(BatchTaskWorker batchTaskWorker) {
        Client.batchTaskWorker = batchTaskWorker;
    }

    public synchronized static ZooKeeperItemTaskDataManager getZooKeeperItemTaskDataManager() throws Exception {
        if (!inited) {
            init();
        }
        return itemTaskWorker.getZooKeeperItemTaskDataManager();
    }

    public synchronized static ZooKeeperBatchTaskDataManager getZooKeeperBatchTaskDataManager() throws Exception {
        if (!inited) {
            init();
        }
        return batchTaskWorker.getZooKeeperBatchTaskDataManager();
    }
}
